//现在
"ui";
ui.layout(
  <vertical>
  <appbar>
  <toolbar  title="v6.4宇博辅助群710441725"  />
  <tabs  id="tabs"  />
  </appbar>
  <Switch   id="autoService" text="无障碍服务" checked="{{auto.service != null}}" />
  <viewpager id="v">
  <ScrollView>
  <vertical>
  <text text="》》》请开启无障碍服务,输入激活码后点击运行！《《《" textColor="red" />
  <horizontal>
  <text text="最低直播时间: " textColor="black" textSize = "15" />
  <input id="times" hint="      " inputType = "number" textSize = "15" text = "35" gravity="center" textColor="red" />
  <text text="分钟  最低收益:" textColor="black" textSize = "15" />
  <input id="gold" hint="      " inputType = "number" textSize = "15" text = "3" gravity="center"  textColor="red" />
  <text text="金币/分钟" textColor="black" textSize = "15" />
  </horizontal>   
  <horizontal>
  <text text="提前 " textColor="black" textSize = "15" />  
  <input id="over_times" hint="      " inputType = "number" textSize = "15" text = "1" gravity="center" textColor="red" />
  <text text="分钟点分享链接" textColor="black" textSize = "15" /> 
  <checkbox id="redheart" text="点红心" textColor="black" textSize = "15"  checked="true" />
  <input id="redheart_second" hint="      " inputType = "number" textSize = "15" text = "50" gravity="center" textColor="red" />
  <text text="下/单" textColor="black" textSize = "15" /> 
  </horizontal>
  <horizontal>
  <text text="抢单优先权:" textSize = "15" textColor="black"  />
  <spinner id="sp2" entries="金币优先|时间优先|规定金币" textColor="blue" /> //选择框
  <checkbox id="slide_down" text="刷新下拉列表" textColor="black" textSize = "15"   />
  </horizontal>
  <horizontal> //水平布局
  <text text="抢到单后" textSize = "15" textColor="black"  />
  <spinner id="sp1" entries="直接打开直播|延时打开直播|停止运行脚本" textColor="red" /> //选择框
  <text text="延时：" textColor="black" textSize = "15" />     
  <input id="id_delayed_times" hint="      " inputType = "number" textSize = "15" text = "5" gravity="center" textColor="red" />
  <text text="秒开" textColor="black" textSize = "15" /> 
  </horizontal>
  <horizontal>
  <text text="屏蔽关键词(单子标题)：" textSize = "15" textColor="black"  />
  <input id="id_shield_title" hint="关键词用'，'隔开 "  textSize = "15" text = " "  textColor="red"  w="*" h="auto"  />
  </horizontal>
  <horizontal>
  <text text="下拉随机刷新" textSize = "15" textColor="black"  gravity="center" />   
  <input id="random_time_min" hint="  "  textSize = "15" text = "10"  textColor="red"  gravity="center" inputType="number"  />
  <text text="---" textSize = "15" textColor="black"  gravity="center"  />   
  <input id="random_time_max" hint="  "  textSize = "15" text = "30"  textColor="red"  gravity="center" inputType="number"  />
  <text text="秒 " textSize = "15" textColor="black"  gravity="center" />   
  <checkbox id="zhendong" text="接单后震动手机" textColor="black" textSize = "15"  checked="true" />
  </horizontal>

  <text text="↓↓↓以下功能未开启↓↓↓" textSize = "15" textColor="#8600FF"  gravity="center" />   
  <horizontal>
  <checkbox id="set_time" text="开启定时功能" textColor="black" textSize = "15"  />
  <text text="启动：" textColor="black" textSize = "15" textColor="red" />  
  <input id="random_time_star" hint="  "  textSize = "15" text = "12:00"  textColor="red"  gravity="center" inputType="number"  />
  <text text="停止：" textColor="black" textSize = "15" textColor="red" />  
  <input id="random_time_stop" hint="  "  textSize = "15" text = "24:00"  textColor="red"  gravity="center" inputType="number"  />
  </horizontal>
  <horizontal>
  <checkbox id="random_speak" text="开启自动发言" textColor="red" textSize = "15" checked="false" />  
  <text text="(如封号,脚本不承认任何后果！)" textColor="black" textSize = "15" textColor="red" />  
  </horizontal>  
  <horizontal>
  <text text="激活码:" textColor="black" textSize = "15" textColor="red" />  
  <input id="code_id" hint="请在此输入激活码！" textColor="grey" w="*" h="auto"  />
  </horizontal>
  <button  id="gm" style="Widget.AppCompat.Button.Colored" text="购买卡密"  layout_gravity="center"  w="*" h="auto" />
  <button  id="bt" style="Widget.AppCompat.Button.Colored" text="开始运行"  layout_gravity="center"  w="*" h="auto" />
  <text text="   欢迎使用雪人辅助！有您的支持，我们才会走的更远O(∩_∩)O..." textColor="red" textSize = "15"  />     

  </vertical>
  </ScrollView>
  </viewpager>
  </vertical>  
);

//网络验证初始化==========
const PJYSDK = (function(){
  function PJYSDK(app_key, app_secret){
      http.__okhttp__.setMaxRetries(0);
      http.__okhttp__.setTimeout(10*1000);

      this.event = events.emitter();

      this.debug = true;
      this._lib_version = "v1.08";
      this._protocol = "https";
      this._host = "api.paojiaoyun.com";
      this._device_id = this.getDeviceID();
      this._retry_count = 9;
      
      this._app_key = app_key;
      this._app_secret = app_secret;
      
      this._card = null;
      this._username = null;
      this._password = null;
      this._token = null;
      
      this.is_trial = false;  // 是否是试用用户
      this.login_result = {
          "card_type": "",
          "expires": "",
          "expires_ts": 0,
          "config": "",
      };

      this._auto_heartbeat = true;  // 是否自动开启心跳任务
      this._heartbeat_gap = 60 * 1000; // 默认60秒
      this._heartbeat_task = null;
      this._heartbeat_ret = {"code": -9, "message": "还未开始验证"};

      this._prev_nonce = null;
  }
  PJYSDK.prototype.SetCard = function(card) {
      this._card = card.trim();
  }
  PJYSDK.prototype.SetUser = function(username, password) {
      this._username = username.trim();
      this._password = password;
  }
  PJYSDK.prototype.getDeviceID = function() {
      let id = device.serial;
      if (id == null || id == "" || id == "unknown") {
          id = device.getAndroidId();
      }
      if (id == null || id == "" || id == "unknown") {
          id = device.getIMEI();
      }
      return id;
  }
  PJYSDK.prototype.MD5 = function(str) {
      try {
          let digest = java.security.MessageDigest.getInstance("md5");
          let result = digest.digest(new java.lang.String(str).getBytes("UTF-8"));
          let buffer = new java.lang.StringBuffer();
          for (let index = 0; index < result.length; index++) {
              let b = result[index];
              let number = b & 0xff;
              let str = java.lang.Integer.toHexString(number);
              if (str.length == 1) {
                  buffer.append("0");
              }
              buffer.append(str);
          }
          return buffer.toString();
      } catch (error) {
          alert(error);
          return "";
      }
  }
  PJYSDK.prototype.getTimestamp = function() {
      try {
          let res = http.get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
          let data = res.body.json();
          return Math.floor(data["data"]["t"]/1000);
      } catch (error) {
          return Math.floor(new Date().getTime()/1000);
      }
  }
  PJYSDK.prototype.genNonce = function() {
      const ascii_str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let tmp = '';
      for(let i = 0; i < 20; i++) {
          tmp += ascii_str.charAt(Math.round(Math.random()*ascii_str.length));
      }
      return this.MD5(this.getDeviceID() + tmp);
  }
  PJYSDK.prototype.joinParams = function(params) {
      let ps = [];
      for (let k in params) {
          ps.push(k + "=" + params[k])
      }
      ps.sort()
      return ps.join("&")
  }
  PJYSDK.prototype.CheckRespSign = function(resp) {
      if (resp.code != 0 && resp.nonce === "" && resp.sign === "") {
          return resp
      }

      let ps = "";
      if (resp["result"]) {
          ps = this.joinParams(resp["result"]);
      }

      let s = resp["code"] + resp["message"] + ps + resp["nonce"] + this._app_secret;
      let sign = this.MD5(s);
      if (sign === resp["sign"]) {
          if (this._prev_nonce === null) {
              this._prev_nonce = resp["nonce"];
              return {"code":0, "message":"OK"};
          } else {
              if (resp["nonce"] > this._prev_nonce) {
                  this._prev_nonce = resp["nonce"];
                  return {"code": 0, "message": "OK"};
              } else {
                  return {"code": -98, "message": "轻点，疼~"};
              }
          }
      }
      return {"code": -99, "message": "轻点，疼~"};
  }
  PJYSDK.prototype.retry_fib = function(num) {
      if (num > 9) {
          return 34
      }
      let a = 0;
      let b = 1;
      for (i = 0; i < num; i++) {
          let tmp = a + b;
          a = b
          b = tmp
      }
      return a
  }
  PJYSDK.prototype._debug = function(path, params, result) {
      if (this.debug) {
          //log("\n" + path, "\nparams:", params, "\nresult:", result);
      }
  }
  PJYSDK.prototype.Request = function(method, path, params) {
      // 构建公共参数
      params["app_key"] = this._app_key;

      method = method.toUpperCase();
      let url = this._protocol + "://" + this._host + path
      let max_retries = this._retry_count;
      let retries_count = 0;

      let data = {"code": -1, "message": "连接服务器失败"};
      do {
          retries_count++;
          let sec = this.retry_fib(retries_count);

          delete params["sign"]
          params["nonce"] = this.genNonce();
          params["timestamp"] = this.getTimestamp();
          let ps = this.joinParams(params);
          let s = method + this._host + path + ps + this._app_secret;
          let sign = this.MD5(s);
          params["sign"] = sign;

          let resp, body;
          try {    
              if (method === "GET") {
                  resp = http.get(url + "?" + ps + "&sign=" + sign);
              } else {  // POST
                  resp = http.post(url, params);
              }
              body = resp.body.string();
              data = JSON.parse(body);
              this._debug(method+'-'+path+':', params, data);
              
              let crs = this.CheckRespSign(data);
              if (crs.code !== 0) {
                  return crs;
              } else {
                  return data;
              }
          } catch (error) {
              log("[*] request error: ", error, sec + "s后重试");
              this._debug(method+'-'+path+':', params, body)
              sleep(sec*1000);
          }
      } while (retries_count < max_retries);

      return data;
  }
  /* 通用 */
  PJYSDK.prototype.GetHeartbeatResult = function() {
      return this._heartbeat_ret;
  }
  PJYSDK.prototype.GetTimeRemaining = function() {
      let g = this.login_result.expires_ts - this.getTimestamp();
      if (g < 0) {
          return 0;
      } 
      return g;
  }
  /* 卡密相关 */
  PJYSDK.prototype.CardLogin = function() {  // 卡密登录
      if (!this._card) {
          return {"code": -4, "message": "请先设置卡密"};
      }
      let method = "POST";
      let path = "/v1/card/login";
      let data = {"card": this._card, "device_id": this._device_id};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this._token = ret.result.token;
          this.login_result = ret.result;
          if (this._auto_heartbeat) {
              this._startCardHeartheat();
          }
      }
      return ret;
  }
  PJYSDK.prototype.CardHeartbeat = function() {  // 卡密心跳，默认会自动调用
      if (!this._token) {
          return {"code": -2, "message": "请在卡密登录成功后调用"};
      }
      let method = "POST";
      let path = "/v1/card/heartbeat";
      let data = {"card": this._card, "token": this._token};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this.login_result.expires = ret.result.expires;
          this.login_result.expires_ts = ret.result.expires_ts;
      }
      return ret;
  }
  PJYSDK.prototype._startCardHeartheat = function() {  // 开启卡密心跳任务
      if (this._heartbeat_task) {
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      this._heartbeat_task = threads.start(function(){
          setInterval(function(){}, 10000);
      });
      this._heartbeat_ret = this.CardHeartbeat();
      
      this._heartbeat_task.setInterval((self) => {
          self._heartbeat_ret = self.CardHeartbeat();
          if (self._heartbeat_ret.code != 0) {
              self.event.emit("heartbeat_failed", self._heartbeat_ret);
          }
      }, this._heartbeat_gap, this);

      this._heartbeat_task.setInterval((self) => {
          if (self.GetTimeRemaining() == 0) {
              self.event.emit("heartbeat_failed", {"code": 10210, "message": "卡密已过期！"});
          }
      }, 1000, this);
  }
  PJYSDK.prototype.CardLogout = function() {  // 卡密退出登录
      this._heartbeat_ret = {"code": -9, "message": "还未开始验证"};
      if (this._heartbeat_task) { // 结束心跳任务
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      if (!this._token) {
          return {"code": 0, "message": "OK"};
      }
      let method = "POST";
      let path = "/v1/card/logout";
      let data = {"card": this._card, "token": this._token};
      let ret = this.Request(method, path, data);
      // 清理
      this._token = null;
      this.login_result = {
          "card_type": "",
          "expires": "",
          "expires_ts": 0,
          "config": "",
      };
      return ret;
  }
  PJYSDK.prototype.CardUnbindDevice = function() { // 卡密解绑设备，需开发者后台配置
      if (!this._token) {
          return {"code": -2, "message": "请在卡密登录成功后调用"};
      }
      let method = "POST";
      let path = "/v1/card/unbind_device";
      let data = {"card": this._card, "device_id": this._device_id, "token": this._token};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.SetCardUnbindPassword = function(password) { // 自定义设置解绑密码
      if (!this._token) {
          return {"code": -2, "message": "请在卡密登录成功后调用"};
      }
      let method = "POST";
      let path = "/v1/card/unbind_password";
      let data = {"card": this._card, "password": password, "token": this._token};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.CardUnbindDeviceByPassword = function(password) { // 用户通过解绑密码解绑设备
      let method = "POST";
      let path = "/v1/card/unbind_device/by_password";
      let data = {"card": this._card, "password": password};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.CardRecharge = function(card, use_card) { // 以卡充卡
      let method = "POST";
      let path = "/v1/card/recharge";
      let data = {"card": card, "use_card": use_card};
      return this.Request(method, path, data);
  }
  /* 用户相关 */
  PJYSDK.prototype.UserRegister = function(username, password, card) {  // 用户注册（通过卡密）
      let method = "POST";
      let path = "/v1/user/register";
      let data = {"username": username, "password": password, "card": card, "device_id": this._device_id};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UserLogin = function() {  // 用户账号登录
      if (!this._username || !this._password) {
          return {"code": -4, "message": "请先设置用户账号密码"};
      }
      let method = "POST";
      let path = "/v1/user/login";
      let data = {"username": this._username, "password": this._password, "device_id": this._device_id};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this._token = ret.result.token;
          this.login_result = ret.result;
          if (this._auto_heartbeat) {
              this._startUserHeartheat();
          }
      }
      return ret;
  }
  PJYSDK.prototype.UserHeartbeat = function() {  // 用户心跳，默认会自动开启
      if (!this._token) {
          return {"code": -2, "message": "请在用户登录成功后调用"};
      }
      let method = "POST";
      let path = "/v1/user/heartbeat";
      let data = {"username": this._username, "token": this._token};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this.login_result.expires = ret.result.expires;
          this.login_result.expires_ts = ret.result.expires_ts;
      }
      return ret;
  }
  PJYSDK.prototype._startUserHeartheat = function() {  // 开启用户心跳任务
      if (this._heartbeat_task) {
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      this._heartbeat_task = threads.start(function(){
          setInterval(function(){}, 10000);
      });
      this._heartbeat_ret = this.UserHeartbeat();

      this._heartbeat_task.setInterval((self) => {
          self._heartbeat_ret = self.UserHeartbeat();
          if (self._heartbeat_ret.code != 0) {
              self.event.emit("heartbeat_failed", self._heartbeat_ret);
          }
      }, this._heartbeat_gap, this);

      this._heartbeat_task.setInterval((self) => {
          if (self.GetTimeRemaining() == 0) {
              self.event.emit("heartbeat_failed", {"code": 10250, "message": "用户已到期！"});
          }
      }, 1000, this);
  }
  PJYSDK.prototype.UserLogout = function() {  // 用户退出登录
      this._heartbeat_ret = {"code": -9, "message": "还未开始验证"};
      if (this._heartbeat_task) { // 结束心跳任务
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      if (!this._token) {
          return {"code": 0, "message": "OK"};
      }
      let method = "POST";
      let path = "/v1/user/logout";
      let data = {"username": this._username, "token": this._token};
      let ret = this.Request(method, path, data);
      // 清理
      this._token = null;
      this.login_result = {
          "card_type": "",
          "expires": "",
          "expires_ts": 0,
          "config": "",
      };
      return ret;
  }
  PJYSDK.prototype.UserChangePassword = function(username, password, new_password) {  // 用户修改密码
      let method = "POST";
      let path = "/v1/user/password";
      let data = {"username": username, "password": password, "new_password": new_password};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UserRecharge = function(username, card) { // 用户通过卡密充值
      let method = "POST";
      let path = "/v1/user/recharge";
      let data = {"username": username, "card": card};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UserUnbindDevice = function() { // 用户解绑设备，需开发者后台配置
      if (!this._token) {
          return {"code": -2, "message": "请在用户登录成功后调用"};
      }
      let method = "POST";
      let path = "/v1/user/unbind_device";
      let data = {"username": this._username, "device_id": this._device_id, "token": this._token};
      return this.Request(method, path, data);
  }
  /* 配置相关 */
  PJYSDK.prototype.GetCardConfig = function() { // 获取卡密配置
      let method = "GET";
      let path = "/v1/card/config";
      let data = {"card": this._card};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UpdateCardConfig = function(config) { // 更新卡密配置
      let method = "POST";
      let path = "/v1/card/config";
      let data = {"card": this._card, "config": config};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.GetUserConfig = function() { // 获取用户配置
      let method = "GET";
      let path = "/v1/user/config";
      let data = {"user": this._username};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UpdateUserConfig = function(config) { // 更新用户配置
      let method = "POST";
      let path = "/v1/user/config";
      let data = {"username": this._username, "config": config};
      return this.Request(method, path, data);
  }
  /* 软件相关 */
  PJYSDK.prototype.GetSoftwareConfig = function() { // 获取软件配置
      let method = "GET";
      let path = "/v1/software/config";
      return this.Request(method, path, {});
  }
  PJYSDK.prototype.GetSoftwareNotice = function() { // 获取软件通知
      let method = "GET";
      let path = "/v1/software/notice";
      return this.Request(method, path, {});
  }
  PJYSDK.prototype.GetSoftwareLatestVersion = function(current_ver) { // 获取软件最新版本
      let method = "GET";
      let path = "/v1/software/latest_ver";
      let data = {"version": current_ver};
      return this.Request(method, path, data);
  }
  /* 试用功能 */
  PJYSDK.prototype.TrialLogin = function() {  // 试用登录
      let method = "POST";
      let path = "/v1/trial/login";
      let data = {"device_id": this._device_id};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this.is_trial = true;
          this.login_result = ret.result;
          if (this._auto_heartbeat) {
              this._startTrialHeartheat();
          }
      }
      return ret;
  }
  PJYSDK.prototype.TrialHeartbeat = function() {  // 试用心跳，默认会自动调用
      let method = "POST";
      let path = "/v1/trial/heartbeat";
      let data = {"device_id": this._device_id};
      let ret = this.Request(method, path, data);
      if (ret.code == 0) {
          this.login_result.expires = ret.result.expires;
          this.login_result.expires_ts = ret.result.expires_ts;
      }
      return ret;
  }
  PJYSDK.prototype._startTrialHeartheat = function() {  // 开启试用心跳任务
      if (this._heartbeat_task) {
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      this._heartbeat_task = threads.start(function(){
          setInterval(function(){}, 10000);
      });
      this._heartbeat_ret = this.TrialHeartbeat();

      this._heartbeat_task.setInterval((self) => {
          self._heartbeat_ret = self.CardHeartbeat();
          if (self._heartbeat_ret.code != 0) {
              self.event.emit("heartbeat_failed", self._heartbeat_ret);
          }
      }, this._heartbeat_gap, this);

      this._heartbeat_task.setInterval((self) => {
          if (self.GetTimeRemaining() == 0) {
              self.event.emit("heartbeat_failed", {"code": 10407, "message": "试用已到期！"});
          }
      }, 1000, this);
  }
  PJYSDK.prototype.TrialLogout = function() {  // 试用退出登录，没有http请求，只是清理本地记录
      this.is_trial = false;
      this._heartbeat_ret = {"code": -9, "message": "还未开始验证"};
      if (this._heartbeat_task) { // 结束心跳任务
          this._heartbeat_task.interrupt();
          this._heartbeat_task = null;
      }
      // 清理
      this._token = null;
      this.login_result = {
          "card_type": "",
          "expires": "",
          "expires_ts": 0,
          "config": "",
      };
      return {"code": 0, "message": "OK"};;
  }
  /* 高级功能 */
  PJYSDK.prototype.GetRemoteVar = function(key) { // 获取远程变量
      let method = "GET";
      let path = "/v1/af/remote_var";
      let data = {"key": key};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.GetRemoteData = function(key) { // 获取远程数据
      let method = "GET";
      let path = "/v1/af/remote_data";
      let data = {"key": key};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.CreateRemoteData = function(key, value) { // 创建远程数据
      let method = "POST";
      let path = "/v1/af/remote_data";
      let data = {"action": "create", "key": key, "value": value};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.UpdateRemoteData = function(key, value) { // 修改远程数据
      let method = "POST";
      let path = "/v1/af/remote_data";
      let data = {"action": "update", "key": key, "value": value};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.DeleteRemoteData = function(key, value) { // 删除远程数据
      let method = "POST";
      let path = "/v1/af/remote_data";
      let data = {"action": "delete", "key": key};
      return this.Request(method, path, data);
  }
  PJYSDK.prototype.CallRemoteFunc = function(func_name, params) { // 执行远程函数
      let method = "POST";
      let path = "/v1/af/call_remote_func";
      let ps = JSON.stringify(params);
      let data = {"func_name": func_name, "params": ps};
      let ret = this.Request(method, path, data);
      if (ret.code == 0 && ret.result.return) {
          ret.result = JSON.parse(ret.result.return);
      }
      return ret;
  }
  return PJYSDK;
})();
let pjysdk = new PJYSDK("bto9gu4o6itf6877el6g", "ZSwSOOZAN2CHuuPfr5FRwd4AVog70GX2"); 
pjysdk._protocol = "https"
pjysdk.debug = true;
//====================
var 本地存储=storages.create("710441725")
取_存储数据(本地存储)
http.__okhttp__.setTimeout(30 * 1000);//HTTP请求超时
ui.v.setTitles(["抖音聚流自助抢单"])
ui.tabs.setupWithViewPager(ui.v);
ui.autoService.on("check",function(checked){

  if(checked && auto.service == null) {
    app.startActivity({
      action: "android.settings.ACCESSIBILITY_SETTINGS"
    });
  }
  if(!checked && auto.service != null){
    auto.service.disableSelf();
  }
})
//打开购买卡密网站
/*
ui.code_ie.click(function(){
  //通过getText()获取输入的内容
  app.openUrl("https://dwz.cn/dXkraS8q");
});
*/
// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function() {
  // 此时根据无障碍服务的开启情况，同步开关的状态
  ui.autoService.checked = auto.service != null;
});
// 点击运行按钮 ,启动程序 
ui.bt.click(function(){
  if(auto.service==null){toast("请开启无障碍服务");return;}
 
  存储数据(本地存储)
  threads.start(程序) // 开启程序线程
  threads.start(单子返回) 
})

//==============================================
//=============================================

function 程序(版本号){
    setScreenMetrics(1080, 1920)
    if(网络验证初始化(版本号)){
      sleep(1000)
      var 启动=launch("uni.yubo"); sleep(3000); if (启动) {toast("APP启动成功,程序开始执行")}
      var 设置_time = ui.times.getText(); var 设置_gold = ui.gold.getText(); var 取消计次 = 0
      var random_time_min = ui.random_time_min.getText(); var random_time_max = ui.random_time_max.getText();var 当前循环禁用标题 = null
      var 屏蔽关键词 = ui.id_shield_title.text(); var 异常累计 = 0
      var 优先选项 =ui.sp2.getSelectedItemPosition();
      while(true){ 
        var random_Refresh =  random(parseInt(random_time_min),parseInt(random_time_max))  
        toast(random_Refresh+"  秒后刷新...");当前循环禁用标题 = null;var 最大金币 = "0";var 标题 = "";var 优选时间 = "0"
        for (a=0;a<random_Refresh;a++){
          var Not_full = text("未满").depth("15").find() ; var 点击领取单子 = false;
          if (Not_full!= null  ){ //获取符合要求的单子，并且判断是否为空
            for (i=0;i<Not_full.length;i++){ //获取单子数量
                if (Not_full[i].parent()!=null){
                    var 父控件 = Not_full[i].parent().parent()
                    if (父控件){ 当前标题 = 父控件.child(1).text();时间文本 = 父控件.child(4).text();金币文本 = 父控件.child(3).text(); }
                    if (判断时间(时间文本,设置_time)&&判断金币(金币文本,设置_gold)){
                       if(parseInt(优先选项)==0){
                        if(金币文本>最大金币){
                            log(标题+' 满足时间：'+parseInt(时间文本.substring(1).substring(1).substring(1).substring(1).substring(1))+"分钟"+最大金币)
                            最大金币 = 金币文本 ; var 时间 = 时间文本 ; 标题 = 当前标题; 点击控件 = 父控件
                        }
                       }else if(parseInt(优先选项)==1){
                        var 分钟 = parseInt(时间文本.substring(1).substring(1).substring(1).substring(1).substring(1))
                        if(分钟>优选时间){
                            最大金币 = 金币文本 ; var 时间 = 时间文本 ; 标题 = 当前标题; 点击控件 = 父控件; 优选时间 = 分钟
                        }
                       }else if(parseInt(优先选项)==2){
                          最大金币 = 金币文本 ; var 时间 = 时间文本 ; 标题 = 当前标题; 点击控件 = 父控件 ; break
                       }
                    }
                }
                sleep(200)
            }
            if(最大金币>"0"){
                if (当前循环禁用标题!=null){ var 屏蔽状态 = 判断单子标题(屏蔽关键词+','+当前循环禁用标题,标题) }else{  var 屏蔽状态 = 判断单子标题(屏蔽关键词,标题)}
                if(屏蔽状态!=true ){ toastLog(标题+' 满足时间：'+parseInt(时间.substring(1).substring(1).substring(1).substring(1).substring(1))+"分钟"+最大金币);点击控件.click(); 点击领取单子 = true; sleep(5000); 异常累计++}
            }
          }
          if (点击领取单子){
            if(取消计次<2){
                var 取消接单 = text("取消接单").findOnce();
                if(取消接单){  取消接单.click() ;异常累计 = 0; for(jishi=0;jishi<5;jishi++){ toast("卡接单"+取消计次+'次 '+String(30-jishi*6)+"秒后运行");sleep(6000)} ; 取消计次++;break }
            }
            else{
                var 继续接单 = text("继续接单").findOnce();if( 继续接单){ 继续接单.click();异常累计 = 0;sleep(5000); 取消计次 = 0 }
            }
          }
          var 直播状态 = 判断是否打开直播()
          if(直播状态==="0"){ 
              判断关注();再次判断关注();
              if(等待直播(时间,最大金币)){ 分享直播链接();  取消计次 = 0;异常累计 = 0} ;break}
          else if(直播状态==="1"){
              if (当前循环禁用标题!=null&& 标题!=null){  
                  当前循环禁用标题= 当前循环禁用标题+','+ 标题 
              }else if (当前循环禁用标题==null&& 标题!=null){
                  当前循环禁用标题= 标题
              }
              异常累计 = 0
           }
          未开播检测()
          if(异常累计>3){重启宇博APP();异常累计 = 0;break}
          sleep(900) 
        }
        //刷新
        toastLog('刷新咯!刷刷新，点点赞，一起撸撸小宇博...')
        if(gesture(500, [500, 400], [500, 1200])==false){toastLog('模拟滑动失败，请重启脚本！')}         
        sleep(1000)  
        if(ui.slide_down.checked){
            gesture(500, [500, 1200], [500, 400]);sleep(1000);gesture(500, [500, 1200], [500, 400])
            sleep(1000)
            gesture(500, [500, 400], [500, 1200]);sleep(1000);gesture(500, [500, 400], [500, 1200])
        }
        if(text('首页').depth('10').findOnce()){}else{ launch("uni.yubo");sleep(5000)}
     }      
    }
}
function 重启宇博APP(){
  关闭应用("uni.yubo");sleep(3000);home();sleep(2000)
  launch("uni.yubo");sleep(1000)
  var 桌面查找 = text('宇博聚流').findOnce()
  if(桌面查找){桌面查找.click();sleep(5000)}
}
function 再次判断关注(){
        toastLog("再次判断关注");sleep(3000)
        var 主播首页 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").desc("主播个人信息").depth("17").clickable().findOnce();
        var 主播首页1 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("jn").depth("17").clickable().findOnce();
        var 主播首页2 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("j_").depth("17").clickable().findOnce();
        var 主播首页3 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("ji").depth("17").clickable().findOnce();
        if(主播首页){主播首页.click()}
        else if(主播首页1){ 主播首页1.click()}
        else if(主播首页2){ 主播首页2.click()}
        else if(主播首页3){ 主播首页3.click()}
        if (主播首页1||主播首页||主播首页2||主播首页3){
              sleep(3000)
              var 未关注 = text("+关注").clickable().findOnce()
              if(未关注){ 未关注.click(); sleep(500);back();return  } 
              else{ 
                 var 已关注 = text("已关注").clickable().findOnce()
                 if (已关注){ sleep(3000) ; back() ; return
               } 
               sleep(1000) 
            }
        }
        else{
            toastLog("找不到主播首页控件！");sleep(2000)
        }

}
function 判断是否打开直播(){
    var 打开直播 = text("打开看看").findOnce();
    if (打开直播){
        判断打开直播选择()
        打开直播.click(); toastLog("哇塞! ヾ(*´▽‘*)ﾉ进来啦!10秒后关注！");
        if(ui.zhendong.checked){  device.vibrate(2000);}
        setClip(""); sleep(10000); return "0"
    }      
    else{
       var 领取其他任务= text("领取其他任务").clickable().findOnce();
       if(领取其他任务){领取其他任务.click();sleep(1000); return "1" }
    }
}
function 未开播检测(){
    var 主播未开播 = text("看看TA的主页").findOnce();
    if (主播未开播){
      toastLog("检测到未开播！返回重新查找。") 
      launch("uni.yubo");sleep(5000);setClip("");
    }
}
function 单子返回(){
    while(true){
        if(textContains("完成任务时长").findOnce()){back();}
        sleep(5000)
    }
}
function 判断单子标题(设置文本,标题文本){
    
    if (设置文本!=null){
       var 分割_文本 =设置文本.split(",")    
       for (ip=0;ip<=分割_文本.length-1;ip++){
          var 出现位置 = 标题文本.indexOf(分割_文本[ip]); 
          if( 出现位置 >= 0){
             log("出现屏蔽字符串")
            return  true
          }
        }
    }


}
function 判断打开直播选择(){
    var 获取选项 = ui.sp1.getSelectedItemPosition();
    log(获取选项);
    switch(获取选项){
        case 0:
           return;
        case 1:
            var 延时time=ui.id_delayed_times.text();
            for(te=0;te<parseInt(延时time);te++){
                sleep(1000)
            }
            return;
        case 2:
            toastLog("哇塞! ヾ(*´▽‘*)ﾉ进来啦!脚本停止咯！！"); 
            exit();
    } 
}
function 等待直播(star_time,star_gold){
    var 官方_time = parseInt(star_time.substring(1).substring(1).substring(1).substring(1).substring(1));
    var 设置提前时间 = ui.over_times.getText(); var 点赞总次数 = ui.redheart_second.getText()//需要改变的量
    var get_random_click_number = 0 ; //随机点击次数
    var 是否点红心 = ui.redheart.checked
    //初次获得随机属性
    var 总时长 = (官方_time*60)-parseInt(设置提前时间)*60-15
    var random_times = random(1,总时长/2)    //按秒来计算
    var 接单time_star=new Date();悬浮窗(true)
    while(true){
      sleep(980);
      //获取接单开始到现在的时间间隔
      var 当前time_star=new Date();
      var 间隔秒=parseInt((当前time_star.getTime()-接单time_star.getTime())/1000)
      //判断是否到时间点赞
      if(是否点红心&&间隔秒>=random_times&&parseInt(点赞总次数)>get_random_click_number){ //执行点赞
        //匹配成功,执行点击,先获取随机点击次数
        var get_random_click_number = random(1,parseInt(点赞总次数)-get_random_click_number); 显示消息('执行点赞:'+String(get_random_click_number))
        //执行点击
        for(io=0;io<get_random_click_number;io++){click((device.width/4)*3,device.height/2-50);sleep(150);if(io % 20 === 0){sleep(1000)} }
        // 点赞完毕,获取下一个随机时间段
        var random_times = random(间隔秒+1,总时长+总时长/2)  
      } 
      //判断主播是否下播
      if(text("直播已结束").depth("15").findOnce()){
        显示消息("傻逼主播下播,等待180秒后继续..");back();
        for(ie=0;ie<180;ie++){  显示消息("傻逼主播下播,等待"+String((180-ie))+"秒后退出..");sleep(1000) }
        悬浮窗(false) ;sleep(3000);launch("uni.yubo");悬浮窗(false) ;return false
      } 
      //悬浮窗显示
      if(间隔秒 % 10 === 0){
        显示消息( JsPieceNum(总时长-间隔秒,60).split('/')[0] +" 分"+JsPieceNum(总时长-间隔秒,60).split('/')[1]+"秒后停止! 收入："+parseInt(间隔秒/60)*parseInt(star_gold)+"  金币 "+(random_times-间隔秒)+"秒点赞")
      }
      //判断是否到时间退出
      if( 总时长-间隔秒<0){log("计时结束,执行分享直播间");return true;}
    }
}
function 悬浮窗(是否启动){
    if (是否启动){
        var intX=device.width;var intY=device.height;
        window = floaty.window(
        <frame padding="2" alpha="0.7" bg="#7B7B7B" w="300">
            <vertical W="" >
                <ScrollView id="As" h="130" w="300">
                    <text id="Alog" textSize="12sp" textColor="#28FF28" margin="1">运行代码：</text>
                </ScrollView>
            </vertical>
        </frame>
    );
    window.setSize(intX-intX/4,intY/4);
    window.setPosition((intY-intY/1.5)/2,(intX-intX/20)/5);
    }
    else{
        window.close()
    }
   
}
function JsPieceNum(num1,num2){
    var pieNum = parseFloat(num1/num2);
    var result="";
    //判断是否为浮点数(100,12)
    if(isFloatNum(pieNum)){
        //整数部分
        var a = Math.floor(pieNum);
        //余数部分
        var b = parseInt(num1%num2);
        //返回整数+"/"+ 余数
        result = a +"/"+ b;
    }else{
        return "0/0";
    }
    return result;
}
//判断是否为浮点数
function isFloatNum(obj) {
    var reg=/^(-?\d+)(\.\d+)?$/;
    if(reg.test(obj)){
        return true;
    }
    return false;
}
function 分享直播链接(){
  desc("更多").depth("16").findOne().click();sleep(1000);
  text("分享").depth("11").findOne().parent().click();sleep(1000);
  text("复制链接").depth("15").findOne().parent().click();sleep(3000);
  desc("更多").depth("16").findOne().click();sleep(1000);
  text("分享").depth("11").findOne().parent().click();sleep(1000);
  text("复制链接").depth("15").findOne().parent().click();sleep(1000);
  back();sleep(3000);
  var 抖音消息 = text("消息").findOnce();if(抖音消息){抖音消息.parent().parent().click()}
  setClip("");悬浮窗(false);sleep(2000);home();sleep(3000)
  launch("uni.yubo");sleep(5000)
  if(textContains("完成任务").findOnce()){back();sleep(3000);}
  if(text('首页').depth('10').findOnce()==null){
     home();sleep(3000)
     launch("uni.yubo");sleep(1000)
     var 桌面查找 = text('宇博聚流').findOnce()
     if(桌面查找){桌面查找.click();sleep(5000)}
   }
}
function 判断关注(){
    while(true){
    toast("查找关注")
    var 主播首页 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").desc("主播个人信息").depth("17").clickable().findOnce();
    var 主播首页1 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("jn").depth("17").clickable().findOnce();
    var 主播首页2 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("j_").depth("17").clickable().findOnce();
    var 主播首页3 = packageName("com.ss.android.ugc.aweme").className("android.widget.RelativeLayout").id("ji").depth("17").clickable().findOnce();
    if(主播首页){主播首页.click()}
    else if(主播首页1){ 主播首页1.click()}
    else if(主播首页2){ 主播首页2.click()}
    else if(主播首页3){ 主播首页3.click()}
    if (主播首页1||主播首页||主播首页2||主播首页3){
       while(true){
          sleep(3000)
          var 未关注 = text("+关注").clickable().findOnce()
          if(未关注){ 未关注.click(); sleep(500);back();return  } 
          else{ 
             var 已关注 = text("已关注").clickable().findOnce()
             if (已关注){ 
             text("已关注").clickable().findOne().click(); sleep(500)
             text("确定").clickable().findOne().click(); sleep(1000)
             text("+关注").clickable().findOne().click(); sleep(500)
             back() ; return
           } 
           sleep(1000) 
        }
       
       特殊查找关注()
       if (desc("更多").depth("16").findOne()){return };sleep(1000);
       } 
    }
    else{
        toast("找不到主播首页控件！");sleep(2000)
    }
}
}
function 特殊查找关注(){
  while(true){
    toast("查找关注,找不到请手动关注下！")
    var 父控件 = className("android.view.ViewGroup").packageName("com.ss.android.ugc.aweme").depth("13").drawingOrder('1').findOnce()
    if (父控件){
        var 子控件 = className("android.view.ViewGroup").packageName("com.ss.android.ugc.aweme").depth("14").drawingOrder(String(父控件.childCount()-2)).findOnce()
        if (子控件!=null&&子控件.childCount()==0){
                click(子控件.bounds().centerX(),子控件.bounds().centerY()); sleep(2000)
                查找确定(子控件);
        }
        else{
            var 子控件 = className("android.view.ViewGroup").packageName("com.ss.android.ugc.aweme").depth("14").drawingOrder(String(父控件.childCount()-1)).findOnce()
            if (子控件!=null){
                click(子控件.bounds().centerX(),子控件.bounds().centerY()); sleep(2000)
                查找确定(子控件);
            }
        } 
    }
    if (desc("更多").depth("16").findOne()){return };
    sleep(3000);
  }
}
function 查找确定(控件){
    var 确定按钮 = text("确定").clickable().findOnce()
    if(确定按钮){
        确定按钮.click(); sleep(1000)
        click(控件.bounds().centerX(),控件.bounds().centerY()); sleep(1000);
    }
    back()
}
function 判断金币(star_gold,set_gold){
    //log("识别金币"+parseInt(star_gold)+'设置金币:'+parseInt(set_gold))
      if(parseInt(star_gold)>=parseInt(set_gold)){
       // log("金币满足")
        return true
      }
      else{
        return false
      }
}
function 判断时间(star_time,set_time){
    var 分钟 = parseInt(star_time.substring(1).substring(1).substring(1).substring(1).substring(1))
 //   log("识别时间"+parseInt(分钟)+'设置时间:'+parseInt(set_time))
    if (parseInt(set_time)<parseInt(分钟)){
     //   log("时间满足")
        return true
    }
    else{
        return false
    }
}
function 截取字符串(str, inta, intb) {
    if (intb) {
        return str.substr(inta, intb)
    } 
    else {
        return str.substr(inta)
    }
}
function 存储数据(create){
    var 多选项 =ui.sp1.getSelectedItemPosition();
    var 多选项2 =ui.sp2.getSelectedItemPosition();
    var 直播time=ui.times.text();
    var 金币mix=ui.gold.text();
    var 直播over=ui.over_times.text();
    var 红心=ui.redheart_second.text();
    var 激活码=ui.code_id.text();
    var 延时时间=ui.id_delayed_times.text();
    var 屏蔽关键词=ui.id_shield_title.text();
    var random_time_min=ui.random_time_min.text();
    var random_time_max=ui.random_time_max.text();
    create.put("random_time_min",random_time_min)
    create.put("random_time_max",random_time_max)
    create.put("code_id",激活码)
    create.put("times",直播time)
    create.put("gold",金币mix)
    create.put("over_times",直播over)
    create.put("redheart_second",红心)
    create.put("sp1",多选项)
    create.put("sp2",多选项2)
    create.put("id_delayed_times",延时时间)
    create.put("id_shield_title",屏蔽关键词)
  }
function 取_存储数据(create){

  var 内容=create.get("times")
  var 内容1=create.get("gold");
  var 内容2=create.get("over_times");
  var 内容3=create.get("redheart_second");
  var 内容4=create.get("code_id");
  if(内容){ ui.times.setText(内容);}
  if(内容1){ ui.gold.setText(内容1);}
  if(内容2){ ui.over_times.setText(内容2);}
  if(内容3){ ui.redheart_second.setText(内容3);}
  if(内容4){ ui.code_id.setText(内容4);}
  var 内容5=create.get("sp1");
  if(内容5){ ui.sp1.setSelection(parseInt(内容5), true);}
  var 内容6=create.get("id_delayed_times");
  if(内容6){ ui.id_delayed_times.setText(内容6);}
  var 内容7=create.get("id_shield_title");
  if(内容7){ ui.id_shield_title.setText(内容7);}
  var 内容8=create.get("random_time_min");
  if(内容8){ ui.random_time_min.setText(内容8);}
  var 内容9=create.get("random_time_max");
  if(内容9){ ui.random_time_max.setText(内容9);}
  var 内容10=create.get("sp2");
  if(内容10){ ui.sp2.setSelection(parseInt(内容10), true);}
}

function 显示消息(消息内容){
    ui.run(function () {window.Alog.append("\n"+消息内容); window.As.scrollTo(0, window.Alog.getHeight());});
}
/* threads.start(function(){
  const versionName = "抖音聚流 V1.64";
  var  vipname="lichongxiao88"   //换成你的自定义账号 需和脚本云登录的一致
  const baseUrl = "http://www.laobing77.xyz/rgx/";
  var res = http.get(baseUrl + "codelist.php?user="+vipname).body.json();
  var 版本内容 = [];
  try{
      var name = res[0].fileName;
      var 版本内容 = name.slice(name.indexOf("V") + 1, name.indexOf(".j"));
      var ver = versionName.slice(versionName.indexOf("V"), versionName.length).replace(/\D/g, '');
      if (ver < 版本内容.replace(/\D/g, '')) {
    threads.start(function() {
      codePath = engines.myEngine().cwd() + "/main.js";
        files.write(codePath, http.get(baseUrl + "download.php?user="+vipname+"&name=" + name).body.string())
               engines.execScriptFile(codePath);
                   toast("更新版本=>V"+版本内容)
                   exit();
                  })
              } 
  } catch(e) {}
  
}) */

//以下为网络验证代码=============================================================
function 网络验证初始化(){
  var 卡密 = ui.code_id.text(); //获取界面卡密
  pjysdk.SetCard(卡密);
  let login_ret = pjysdk.CardLogin();
  if (login_ret.code == 0) {
    // 登录成功，后面写你的业务代码
    let ret = pjysdk.GetTimeRemaining()
    toastLog("欢迎使用神行辅助!剩余:"+parseInt(ret/60)+"分钟") 
    //获取版本状态("1.37")
    return true
  } 
  else {
  // 登录失败提示
    toast(login_ret.message);
    log("登录失败")
    return false
  }
}
function 获取版本状态(当前版本){
    let 版本属性 = pjysdk.GetSoftwareLatestVersion(当前版本)
    if (版本属性.code==0){
        if(版本属性.result.version==当前版本){log("不需要更新")}else{
            alert("最新版本"+版本属性.result.version+"\n公告:"+版本属性.result.notice);    
        }
    }

}
// 监听心跳失败事件
pjysdk.event.on("heartbeat_failed", function(hret) {
  log("心跳失败，尝试重登...")
  sleep(2000);
  let login_ret = pjysdk.CardLogin();
  if (login_ret.code == 0) {
      log("重登成功");
  } else {
      toastLog(login_ret.message);  // 重登失败
      sleep(200);
      exit();  // 退出脚本
  }
});
// 当脚本正常或者异常退出时会触发exit事件
events.on("exit", function(){
    pjysdk.CardLogout(); // 调用退出登录
   // log("结束运行");
});


function 关闭应用(packageName) {
  //let packageName = currentPackage();
  app.openAppSetting(packageName);
  text(app.getAppName(packageName)).waitFor();  
  sleep(3000)
  let is_sure = textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne();
  if (is_sure.enabled()) {
      textMatches(/(.*强.*|.*停.*|.*结.*|.*行.*)/).findOne().click();
      textMatches(/(.*确.*|.*定.*)/).findOne().click();
      log(app.getAppName(packageName) + "应用已被关闭");
      sleep(1000);
      back();
  } else {
      log(app.getAppName(packageName) + "应用不能被正常关闭或不在后台运行");
      back();
  }
}